package com.qxzn.module.mine.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.lmc.util.ImgCropUrtil;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.AuthInfoBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.robot.PermissionHelper;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfoActivity extends BaseActivity {

    @BindView(R2.id.user_head)
    ImageView userHead;
    @BindView(R2.id.user_nickname)
    TextView userNickname;
    @BindView(R2.id.user_phone)
    TextView userPhone;
    @BindView(R2.id.tv_phone_prompt)
    TextView tv_phone_prompt;

    @BindView(R2.id.reset_family_pwd_btn_line)
    View line;
    @BindView(R2.id.reset_family_pwd_btn)
    View btn;

    boolean isAdmin;

    @Override
    protected int initLayout() {
        return R.layout.activity_user_info;
    }

    private void hideAdminView() {
        isAdmin = false;
        tv_phone_prompt.setText("手机号");
        userPhone.setCompoundDrawables(null, null, null, null);
        line.setVisibility(View.GONE);
        btn.setVisibility(View.GONE);
    }

    private void showAdminView() {
        isAdmin = true;
        tv_phone_prompt.setText(R.string.modify_admin_title);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_chevron_right_24dp);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        userPhone.setCompoundDrawables(null, null, drawable, null);
        line.setVisibility(View.VISIBLE);
        btn.setVisibility(View.VISIBLE);
    }

    private void updateUserInfo() {
        String nickname = SharePreferenceUtil.getNickname(this);
        if (TextUtils.isEmpty(nickname))
            nickname = SharePreferenceUtil.getUserName(this);
        userNickname.setText(nickname);
        userPhone.setText(CommonUtil.getSecurityPhoneString(SharePreferenceUtil.getPhone(this)));
        Glide.with(this)
                .load(SharePreferenceUtil.getPortrait(this))
                .apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.drawable.user_head).error(R.drawable.user_head))
                .into(userHead);
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == Constant.EventBusId.UPDATE_USER_INFO) {
            updateUserInfo();
            getAuthInfo();
        }
    }

    @Override
    protected void initView() {
        hideAdminView();
        updateUserInfo();
    }

    @OnClick({R2.id.user_head, R2.id.user_nickname, R2.id.user_phone_btn, R2.id.user_pwd_btn,
            R2.id.reset_security_pwd_btn, R2.id.reset_family_pwd_btn, R2.id.reset_face_img_btn, R2.id.logout_btn})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) return;
        int i = view.getId();
        if (i == R.id.user_head) {
            PermissionHelper.checkCameraPermission(this, () -> getPicture(1, 1));
        } else if (i == R.id.user_nickname) {
            startActivity(new Intent(this, ModifyNameActivity.class)
                    .putExtra(ModifyNameActivity.EXTRA_TYPE, ModifyNameActivity.TYPE_USER));
        } else if (i == R.id.user_phone_btn) {
            if (isAdmin)
                startActivity(new Intent(this, VerificationCode.class)
                        .putExtra(VerificationCode.EXTRA_TITLE, getString(R.string.modify_admin_title))
                        .putExtra(VerificationCode.EXTRA_TYPE_int, 6)
                        .putExtra(VerificationCode.EXTRA_PHONE, SharePreferenceUtil.getPhone(this))
                        .putExtra(VerificationCode.EXTRA_ACTIVITY, "com.qxzn.module.mine.activity.ModifyPhoneActivity"));
        } else if (i == R.id.user_pwd_btn) {
            startActivity(new Intent(this, VerificationCode.class)
                    .putExtra(VerificationCode.EXTRA_TITLE, "设置登录密码")
                    .putExtra(VerificationCode.EXTRA_TYPE_int, 7)
                    .putExtra(VerificationCode.EXTRA_PHONE, SharePreferenceUtil.getPhone(this))
                    .putExtra(VerificationCode.EXTRA_ACTIVITY, "com.qxzn.module.mine.activity.ModifyPasswordActivity")
                    .putExtra(VerificationCode.EXTRA_ACTIVITY_PARAMS, ModifyPasswordActivity.PARAM_USER));
        } else if (i == R.id.reset_security_pwd_btn) {
            startActivity(new Intent(this, VerificationCode.class)
                    .putExtra(VerificationCode.EXTRA_TITLE, "设置安全密码")
                    .putExtra(VerificationCode.EXTRA_TYPE_int, 8)
                    .putExtra(VerificationCode.EXTRA_PHONE, SharePreferenceUtil.getPhone(this))
                    .putExtra(VerificationCode.EXTRA_ACTIVITY, "com.qxzn.module.mine.activity.ModifyPasswordActivity")
                    .putExtra(VerificationCode.EXTRA_ACTIVITY_PARAMS, ModifyPasswordActivity.PARAM_SECURITY));
        } else if (i == R.id.reset_family_pwd_btn) {
            startActivity(new Intent(this, VerificationCode.class)
                    .putExtra(VerificationCode.EXTRA_TITLE, "设置家庭密码")
                    .putExtra(VerificationCode.EXTRA_TYPE_int, 9)
                    .putExtra(VerificationCode.EXTRA_PHONE, SharePreferenceUtil.getPhone(this))
                    .putExtra(VerificationCode.EXTRA_ACTIVITY, "com.qxzn.module.mine.activity.ModifyPasswordActivity")
                    .putExtra(VerificationCode.EXTRA_ACTIVITY_PARAMS, ModifyPasswordActivity.PARAM_FAMILY));
        } else if (i == R.id.reset_face_img_btn) {
            startActivity(new Intent(this, VerificationCode.class)
                    .putExtra(VerificationCode.EXTRA_TITLE, "重置人脸识别")
                    .putExtra(VerificationCode.EXTRA_TYPE_int, 10)
                    .putExtra(VerificationCode.EXTRA_PHONE, SharePreferenceUtil.getPhone(this))
                    .putExtra(VerificationCode.EXTRA_ACTIVITY, "com.qxzn.module.mine.activity.UpdateFaceActivity"));
//            ToastUtil.showTextToast(getApplicationContext(), "重置人脸照片");
        } else if (i == R.id.logout_btn) {
//            ToastUtil.showTextToast(getApplicationContext(), "退出登录");
            startActivity(new Intent().setComponent(new ComponentName(this, "com.qxzn.app.personalcenter.activity.LoginByPwdActivity")));
            ActivityStack.finishAllWithoutActivity("com.qxzn.app.personalcenter.activity.LoginByPwdActivity");
        }
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("账号信息");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        getAuthInfo();
    }

    private void getAuthInfo() {
        hideAdminView();
        String deviceId = SharePreferenceUtil.getDeviceId(this);
        String userName = SharePreferenceUtil.getUserName(this);
        if (TextUtils.isEmpty(deviceId)) return;
        JSONObject param = new JSONObject();
        param.put("device_id", deviceId);
        HttpRequest.getService().getAuthInfo(HttpRequest.getDefaultBody(param)).enqueue(new Callback<BaseBean<AuthInfoBean>>() {
            @Override
            public void onResponse(Call<BaseBean<AuthInfoBean>> call, Response<BaseBean<AuthInfoBean>> response) {
                hideProgress();
                BaseBean<AuthInfoBean> body = response.body();
                if (body.getCode() == 200) {
                    AuthInfoBean data = body.getData();
                    if ("1".equals(data.user_role)) {
                        if (TextUtils.equals(userName, data.admin_id)) {
                            showAdminView();
                        }
                    }
//                } else {
//                    ToastUtil.showTextToast(UserInfoActivity.this, body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean<AuthInfoBean>> call, Throwable t) {
                hideProgress();
                ToastUtil.showTextToast(UserInfoActivity.this, getString(R.string.network_error));
            }
        });
    }


    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(false)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .showSingleMediaType(false)
                .forResult(requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        List<String> mSelected = Matisse.obtainPathResult(data);
        if (mSelected != null && mSelected.size() > 0) {
            //裁剪图片
            ImgCropUrtil.crop(this, mSelected.get(0), 400, 400);
        }
        if (requestCode == ImgCropUrtil.RESULT_CAMERA_CROP_PATH_RESULT) {
            //上传图片
            upload(ImgCropUrtil.getImageClip());
            Glide.with(this).load(ImgCropUrtil.getImageClip()).apply(new RequestOptions()).into(userHead);
        }
    }

    private void upload(String faceIdPath) {
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(new File(faceIdPath));
        RequestBody username = HttpRequest.getPartBody(SharePreferenceUtil.getUserName(this));
        HttpRequest.getService().uploadUserHeader(username, fileBody).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean body = response.body();
                if (body.getCode() == 200) {
                    SharePreferenceUtil.setPortrait(getApplicationContext(), HttpRequest.BASE_URL + body.getData());
                    EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.UPDATE_USER_INFO).build());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                ToastUtil.showTextToast(UserInfoActivity.this, getString(R.string.network_error));
            }
        });

    }
}
